import React from 'react';
import $ from 'jQuery';
import {AppBar, AppCanvas, ClearFix, LeftNav, List, ListItem, MenuItem, Styles, SvgIcon} from 'material-ui'

let injectTapEventPlugin = require("react-tap-event-plugin");
injectTapEventPlugin();

import './main.less';

const ThemeManager = new Styles.ThemeManager();

/**
 * The abstract class of news panel.
 */
class NewsPanel extends React.Component {
	
	constructor(props) {
		super(props);
		this.state = {news: []};
	}
	
	/**
	 * Fetch the list when component is ready.
	 */
	componentDidMount() {
		$.get(this.props.source, function(news) {
			if (news && news.length) {
				if (this.props.localId) {
					var oldNews = (localStorage.getItem(this.props.localId) && JSON.parse(localStorage.getItem(this.props.localId))) || {};
					news = news.map((n) => {
						n.unread = !oldNews[n.title];
						return n;
					});
				}
				this.setState({
					news: news
				});
			}
		}.bind(this));
	}
	
	/**
	 * Render the notice news panel.
	 */
	render() {
		return (
			<List subheader={this.props.title}>
				{this.state.news.filter((e, i) => {
					return i < this.props.size;
				}).map((n, i) => {
					return this.renderItem(n, i);
				})}
			</List>
		);
	}
	
	read(title, link) {
		window.open(link);
		if (this.props.localId) {
			var oldNews =(localStorage.getItem(this.props.localId) && JSON.parse(localStorage.getItem(this.props.localId)))|| {};
			oldNews[title] = true;
			this.setState({
				news: this.state.news.map((n) => {
					n.unread = !oldNews[n.title];
					return n;
				})
			});
			localStorage.setItem(this.props.localId, JSON.stringify(oldNews));
		}
	}
	
}

NewsPanel.defaultProps = { size: 10 };

class ReadIcon extends React.Component {
	render() {
		return (
			<SvgIcon {...this.props}>
				<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 9h-2V5h2v6zm0 4h-2v-2h2v2z"/>
    			<path d="M0 0h24v24H0z" fill="none"/>
			</SvgIcon>
		)
	}
}

class NoticeNewsPanel extends NewsPanel {
	
	/**
	 * Render the notice item.
	 */
	renderItem(n, i) {
		return (
			<ListItem key={i} 
				primaryText={n.title}
				secondaryText={n.date}
				onClick={this.read.bind(this, n.title, n.link)}
				rightAvatar={n.unread?<ReadIcon />:null}	
			/>
		);
	}

}

class ReportNewsPanel extends NewsPanel {
	
	/**
	 * Render the report item.
	 */
	renderItem(n, i) {
		return (
			<ListItem key={i} 
				primaryText={n.speaker + '报告会'}
				secondaryText={
					<p>
		              	<span style={{color: Styles.Colors.darkBlack}}>{n.date}</span><br/>
		              	{n.title}
		            </p>
				}
				secondaryTextLines={2}
				onClick={this.read.bind(this, n.title, n.link)}
				rightAvatar={n.unread?<ReadIcon />:null}
			/>
		);
	}

}

class AppNav extends React.Component {
	
	constructor(props) {
		super(props);
		this.state = {
			items: []
		};
	}
	
	componentDidMount() {
		this.setState({
			items: [
				{
					type: MenuItem.Types.LINK,
					payload: 'https://git.oschina.net/zhi/neu-news',
					text: 'About'
				}
			]
		})
	}
	
	getStyles() {
		return {
			cursor: 'pointer',
			//.mui-font-style-headline
			fontSize: '24px',
			color: Styles.Typography.textFullWhite,
			lineHeight: Styles.Spacing.desktopKeylineIncrement + 'px',
			fontWeight: Styles.Typography.fontWeightLight,
			backgroundColor: Styles.Colors.cyan500,
			paddingLeft: Styles.Spacing.desktopGutter,
			paddingTop: '0px',
			marginBottom: '8px'
		};
	}
	
	render() {
		let header = (
			<div style={this.getStyles()} onTouchTap= { this._onHeaderClick } >
				Navi.
			</div>
		);
		return <LeftNav ref="leftNav" header={header} docked={false} menuItems={this.state.items} />
	}
	
	toggle() {
		this.refs.leftNav.toggle();
	}
	
	_onHeaderClick() {
		this.refs.leftNav.close();
	}
}

class MainApp extends React.Component {
	
	getChildContext() {
		return {
			muiTheme: ThemeManager.getCurrentTheme()
		};
	}
	
	_toggleNavigation() {
		this.refs.leftNav.toggle();
	}
	
	render() {
		return (
			<AppCanvas>
				<AppBar 
					title="NEU News" 
					onLeftIconButtonTouchTap={this._toggleNavigation.bind(this)}
				/>
				
				<AppNav ref="leftNav" />
				
				<ClearFix style={{paddingTop: '64px'}}>
					<NoticeNewsPanel localId="news-sc" title="软件学院研究生通知" source="/scholar/scNews.json" />
					<ReportNewsPanel localId="news-ise" title="信息学院报告通知" source="/scholar/iseReport.json" />
				</ClearFix>
			</AppCanvas>
		)
	}
	
}

MainApp.childContextTypes = {
	muiTheme: React.PropTypes.object
};

React.render(
	<MainApp />,
	document.body
)

// // Software College
// React.render(
// 	<NoticeNewsPanel localId="news-sc" title="软件学院研究生通知" source="/scholar/scNews.json" />,
// 	document.getElementById('news-sc')
// );

// // ISE
// React.render(
// 	<ReportNewsPanel localId="news-ise" title="信息学院报告通知" source="/scholar/iseReport.json" />,
// 	document.getElementById('news-ise')
// )